package com.suneast.suneaststore.modules.personal.sign;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.suneast.suneaststore.R;
import com.suneast.suneaststore.modules.personal.sign.event.AuthCodeGotEvent;
import com.suneast.suneaststore.modules.personal.sign.event.CountDownEvent;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.personal.sign.event.RequestAutoCodeResult;
import com.suneast.suneaststore.modules.personal.sign.event.SignInResult;
import com.suneast.suneaststore.modules.wechat.LatteWeChat;
import com.suneast.suneaststore.ui.fragments.BaseFragment;
import com.suneast.suneaststore.util.regex.RegexUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class SignInFragment extends BaseFragment {

    private int state = 0; // 0 正常登陆  1: 登陆过期后进来的

    public SignInFragment withState(int state) {
        this.state = state;
        return this;
    }

    @Override
    public @LayoutRes
    int setLayout() {
        return R.layout.fragment_sign_in;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        initView();
    }

    @Override
    public void onDestroyView() {
        timer.cancel();
        if (task != null) {
            task.cancel();
        }
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @OnClick({R.id.tv_register, R.id.btn_login, R.id.btn_request_code,
            R.id.tv_forget_password, R.id.img_wx_login})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.tv_register: {
                start(new SignUpFragment());
            }
            break;
            case R.id.btn_login: {
                if (isMsgCodeType) {
                    Log.e("test", "onViewClick: phoneNumber = " + phoneNumber + " authcode = " + passWord);
                    SignRequestHandler.signInByAuthCode(phoneNumber, passWord);
                } else {
                    SignRequestHandler.signInByPassWord(phoneNumber, passWord);
                }
            }
            break;
            case R.id.btn_request_code: {
                if (RegexUtil.isMobile(phoneNumber)) {
                    getCodeBtn.setEnabled(false);
                    SignRequestHandler.requestAuthCode(phoneNumber, Flag.CodeType.AUTH_CODE);
                } else {
                    Toast.makeText(getContext(), "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                }
            }
            break;
            case R.id.tv_forget_password: {
                ResetPwdFragment fragment = new ResetPwdFragment();
                Bundle bundle = new Bundle();
                bundle.putString("number", phoneNumber);
                fragment.setArguments(bundle);
                start(fragment);
            }
            break;
            case R.id.img_wx_login: {
                if (!LatteWeChat.getInstance().getWXAPI().isWXAppInstalled()) {
                    Toast.makeText(getContext(), "该设备没有安装微信", Toast.LENGTH_SHORT).show();
                } else {
                    LatteWeChat.getInstance().signIn();
                }
            }
            break;
        }
    }

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.edit_text_phone_number)
    EditText phoneNumberEdit;

    @BindView(R.id.edit_text_password)
    EditText passWordEdit;

    @BindView(R.id.btn_request_code)
    Button getCodeBtn;

    @BindView(R.id.btn_login)
    Button loginBtn;

    @BindView(R.id.img_password)
    ImageView passwordImg;

    @BindView(R.id.cb_change_login_type)
    CheckBox changeLoginTypeCb;

    private boolean isMsgCodeType = false;

    private String phoneNumber = "";
    private String passWord = "";

    private void initView() {
        toolbar.setNavigationOnClickListener(v -> {
            if (state == 0) {
                pop();
            } else {
                if (getActivity() != null) {
                    getActivity().finish();
                }
            }
        });
        phoneNumberEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                phoneNumber = s.toString();
                checkLoginBtn();
            }
        });
        passWordEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                passWord = s.toString();
                checkLoginBtn();
            }
        });
        changeLoginTypeCb.setOnCheckedChangeListener((CompoundButton buttonView, boolean isChecked)
                -> {
            getCodeBtn.setVisibility(isChecked ? View.VISIBLE : View.GONE);
            passWordEdit.setHint(getResources()
                    .getString(isChecked ? R.string.input_auth_code : R.string.input_password));
            buttonView
                    .setText(isChecked ? R.string.password_login : R.string.message_code_login);
            passWordEdit.setText("");
            passWord = "";
            passWordEdit.setInputType(isChecked ? InputType.TYPE_CLASS_NUMBER
                    : InputType.TYPE_TEXT_VARIATION_PASSWORD);
            passwordImg.setImageResource(isChecked ?
                    R.drawable.ic_auth_code
                    : R.drawable.ic_password);
            isMsgCodeType = isChecked;
        });
        timer = new Timer();
    }

    private int count = 90;
    private TimerTask task;
    private Timer timer;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCountDown(CountDownEvent event) {
        if (event.getType() == Flag.CodeType.AUTH_CODE) {
            if (count > 0) {
                getCodeBtn.setText(count + getResources().getString(R.string.afresh_auto_code));
                count--;
            } else {
                task.cancel();
                getCodeBtn.setEnabled(true);
                getCodeBtn.setText(getResources().getString(R.string.get_auth_code));
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotAuthCode(AuthCodeGotEvent event) {
        passWord = event.getAuthCode();
        passWordEdit.setText(String.valueOf(passWord));
        if (RegexUtil.isMobile(phoneNumber) && passWordEdit.length() > 0) {
            loginBtn.setEnabled(true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRequestAutoCodeResult(RequestAutoCodeResult event) {
        switch (event.getState()) {
            case Flag.Result.SUCCEED: {
                count = 90;
                task = new TimerTask() {
                    @Override
                    public void run() {
                        EventBus.getDefault().post(new CountDownEvent(Flag.CodeType.AUTH_CODE));
                    }
                };
                timer.schedule(task, 0, 1000);
            }
            break;
            case Flag.Result.FAILURE: {
                getCodeBtn.setEnabled(true);
            }
            break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSignInState(SignInResult event) {
        switch (event.getState()) {
            case Flag.Result.SUCCEED: {
                Toast.makeText(getContext(), "登录成功", Toast.LENGTH_SHORT).show();
                pop();
            }
            break;
            case Flag.Result.FAILURE: {
                Toast.makeText(getContext(), "登录失败", Toast.LENGTH_SHORT).show();
            }
            break;
        }
    }

    private void checkLoginBtn() {
        if (isMsgCodeType) {
            loginBtn.setEnabled(phoneNumber.length() == 11 && passWord.length() == 4);
        } else {
            loginBtn.setEnabled(phoneNumber.length() == 11 && passWord.length() >= 6);
        }
    }
}
